/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package parismetro;

/**
 * @author kevin
 */

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.CustomNode;
import javafx.geometry.Rectangle2D;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.control.ListView;
import javafx.scene.layout.LayoutInfo;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.CacheHint;
import javafx.scene.control.ListCell;
import javafx.scene.control.Label;
import modele.RERTicket;


public class Map extends CustomNode {

    var group: Group;
    public var main: Main;
    var zoomLevel:Integer = 0;

    var nearbyStations:String[] = [] ;
    var viewportCenterX: Number =2120;
    var viewportCenterY: Number =2120;
    var viewportSize: Number = 4240;
    def offsetMove = 80;
    def searchRadius = 90;

    public var isDialogDiplayed = false;
    public var choixStation : ChoixStation;
    var departureSelect = false;

def fileDataSource: org.netbeans.javafx.datasrc.HttpDataSource = org.netbeans.javafx.datasrc.HttpDataSource {
        url: "http://kraynel.free.fr/positionsStations.xml"
        parser: org.netbeans.javafx.datasrc.Parsers.XML_PARSER
    }


    // load the image
def metromap = Image {
    url: "{__DIR__}icons/metro.png"
}

def urliconplus = Image {
     url: "{__DIR__}icons/icon_plus.png"
}

def urliconminus = Image {
     url: "{__DIR__}icons/icon_minus.png"
}

def urlarrowleft = Image {
     url: "{__DIR__}icons/arrow_left.png"
}

def urlarrowright = Image {
     url: "{__DIR__}icons/arrow_right.png"
}

def urlarrowup = Image {
     url: "{__DIR__}icons/arrow_up.png"
}

def urlarrowdown = Image {
     url: "{__DIR__}icons/arrow_down.png"
}

def iv = ImageView {
    image: metromap
    fitWidth: 700;
    viewport: bind Rectangle2D {
        minX: viewportCenterX - viewportSize / 2
        minY: viewportCenterY - viewportSize / 2
        width: viewportSize
        height: viewportSize
    }

    preserveRatio: true
    smooth: true
    cache: true
    x: 50
    y: 34;

    onMouseClicked: function(me: MouseEvent) {
            //println(fileDataSource.path);
        if (me.button == MouseButton.PRIMARY and {zoomLevel}==0) {
            zoomLevel = 1;
            viewportCenterX = (me.sceneX-50)/700*viewportSize;
            viewportCenterY = (me.sceneY-34)/700*viewportSize;
            //println(" {me.sceneX} {me.sceneY} {viewportCenterX} {viewportCenterY}");
            viewportSize = viewportSize/2.5;

             viewportCenterX = java.lang.Math.min(4240-viewportSize/2,
                                java.lang.Math.max(viewportCenterX, viewportSize/2));
            viewportCenterY = java.lang.Math.min(4240-viewportSize/2,
                                java.lang.Math.max(viewportCenterY, viewportSize/2));
                                
            updateNearbyStations(viewportCenterX,viewportCenterY, searchRadius*1.5)
        } else if (me.button == MouseButton.PRIMARY) {
           //viewportCenterX = viewportCenterX - viewportSize/2 + (me.sceneX-50)/700*viewportSize;
           //viewportCenterY = viewportCenterY - viewportSize/2 + (me.sceneY-34)/700*viewportSize;
           updateNearbyStations(viewportCenterX - viewportSize/2 + (me.sceneX-50)/700*viewportSize,viewportCenterY - viewportSize/2 + (me.sceneY-34)/700*viewportSize, searchRadius)
        }


   }

}

def zoomIn = ImageView {
    image: urliconplus
    fitWidth: 50;
    preserveRatio: true
    smooth: true
    cache: true
    x: iv.x + iv.fitWidth + 5;
    y: iv.y;

    onMouseClicked: function(me: MouseEvent) {
        if (me.button == MouseButton.PRIMARY and {zoomLevel}==0) {
            zoomLevel = 1;
            viewportSize = viewportSize/2.5;
            viewportCenterX = 2120;
            viewportCenterY = 2120;
        }
   }
}

def zoomOut = ImageView {
    image: urliconminus
    fitWidth: 50;
    preserveRatio: true
    smooth: true
    cache: true
    x: zoomIn.x + zoomIn.fitWidth + 5;
    y: zoomIn.y;

    onMouseClicked: function(me: MouseEvent) {
        if (me.button == MouseButton.PRIMARY and {zoomLevel}==1) {
            zoomLevel = 0;
            viewportSize = 4240;
            viewportCenterX = 2120;
            viewportCenterY = 2120;
        }
   }
}

def goLeft = ImageView {
    image: urlarrowleft
    fitWidth: 50;
    preserveRatio: true
    smooth: true
    cache: true
    x: iv.x
    y: iv.y + iv.fitWidth/2 -25;

    onMouseClicked: function(me: MouseEvent) {
        if (me.button == MouseButton.PRIMARY and {zoomLevel}==1) {
        viewportCenterX = java.lang.Math.max(viewportCenterX-offsetMove,viewportSize/2);
        }
   }
}

def goRight = ImageView {
    image: urlarrowright
    fitWidth: 50;
    preserveRatio: true
    smooth: true
    cache: true
    x: iv.x + iv.fitWidth - 50;
    y: iv.y + iv.fitWidth/2 -25;

    onMouseClicked: function(me: MouseEvent) {
        if (me.button == MouseButton.PRIMARY and {zoomLevel}==1) {
            viewportCenterX = java.lang.Math.min(viewportCenterX+offsetMove,4240-viewportSize/2);
   }
}
}

def goUp = ImageView {
    image: urlarrowup
    fitWidth: 50;
    preserveRatio: true
    smooth: true
    cache: true
    x: iv.x + iv.fitWidth/2 -25;
    y: iv.y;

    onMouseClicked: function(me: MouseEvent) {
        if (me.button == MouseButton.PRIMARY and {zoomLevel}==1) {
        viewportCenterY = java.lang.Math.max(viewportCenterY-offsetMove,viewportSize/2);
        }
   }
}

def goDown = ImageView {
    image: urlarrowdown
    fitWidth: 50;
    preserveRatio: true
    smooth: true
    cache: true
    x: iv.x + iv.fitWidth/2 -25;
    y: iv.y + iv.fitWidth - 50;

    onMouseClicked: function(me: MouseEvent) {
        if (me.button == MouseButton.PRIMARY and {zoomLevel}==1) {
        viewportCenterY =java.lang.Math.min(viewportCenterY+offsetMove,4240-viewportSize/2);
        }
   }
}
var selectedCell: Integer = -1;

function currentCellFactory():ListCell {
    def cell:ListCell = ListCell {
        node: Label {
        text: bind if (cell.empty) then "" else "{cell.item}"
        onMouseEntered: function(e:MouseEvent) : Void {
            selectedCell = cell.index;
        }
        onMouseExited: function(e:MouseEvent) : Void {
            selectedCell = -1;
        }

        }
    }
}

def listView: javafx.scene.control.ListView = javafx.scene.control.ListView {
        layoutX: zoomIn.x+40;
        layoutY: zoomIn.y + 150 ;
        scaleX: 1.5;
        scaleY: 1.5;
        layoutInfo: LayoutInfo {width:200/1.5 height: (iv.fitWidth - 220)/1.5};
        cellFactory: currentCellFactory;
        items: bind for(record in nearbyStations) record
         //items: bind for(record in fileDataSource.getDataSource("Worksheet/Table/Row/Cell").getRecordSet().all()) record.getString(".text")
        onMouseMoved: function(e:MouseEvent) : Void {
            listView.select(selectedCell);
        }

        onMousePressed: function(e: MouseEvent): Void {
            if(choixStation.departureSelect){
                choixStation.departureStation = listView.selectedItem.toString();
                choixStation.departureSelect = false;
            }else {
                var t:RERTicket = RERTicket{orderList:choixStation.main.orderList, startStation: choixStation.departureStation, endStation:{listView.selectedItem.toString()} };
                choixStation.main.orderList.addOrder(t);
                        //println("Achat de billet vers {listView.selectedItem.toString()}");
               choixStation.stationEnCours = "";
               choixStation.departureStation = main.stationMachine;
               choixStation.departureSelect = false;

               choixStation.main.optionEcran.previousStep = "rer";
               choixStation.main.changeContent("tplus");
            }


                //    main.logger.addEvent("dialogMap", "btnValider", "previousScreen");
                //    choixStation.stationEnCours = listView.selectedItem.toString();
                    zoomLevel = 0;
                    viewportSize = 4240;
                    viewportCenterX = 2120;
                    viewportCenterY = 2120;
                    nearbyStations = [];
                    choixStation.dialog.afficher = false;
                }
    }

def bouton_etape_prec   = Group{
                layoutX:zoomIn.x + 5;
                layoutY:iv.y + iv.fitWidth - 100;
                //effect: shadow;
                content: [
                    Rectangle {
                        height:95
                        width:95
                        arcWidth: 15, arcHeight: 15
                        fill: Color.rgb(0,113,188)
                        stroke: Color.WHITE;
                        strokeWidth: 5;
                    }
                    Text {
                        layoutX:15, layoutY:45
                        font: Font{size:22, embolden:true, name:"Myriad Pro"}
                        content: "Annuler"
                        textAlignment: TextAlignment.CENTER
                        fill: Color.WHITE
                    }
                    ]
               onMousePressed: function(e: MouseEvent): Void {
                    main.logger.addEvent("dialogMap", "btnEtapePrec", "previousScreen");
                    zoomLevel = 0;
                    viewportSize = 4240;
                    viewportCenterX = 2120;
                    viewportCenterY = 2120;
                    nearbyStations = [];
                    choixStation.dialog.afficher = false;
                }
}

def bouton_valider   = Group{
                layoutX:zoomIn.x + 105;
                layoutY:iv.y + iv.fitWidth - 100;
                //effect: shadow;
                content: [
                    Rectangle {
                        height:95
                        width:95
                        arcWidth: 15, arcHeight: 15
                        fill: Color.rgb(0,113,188)
                        stroke: Color.WHITE;
                        strokeWidth: 5;
                    }
                    Text {
                        layoutX:15, layoutY:45
                        font: Font{size:22, embolden:true, name:"Myriad Pro"}
                        content: "Valider"
                        textAlignment: TextAlignment.CENTER
                        fill: Color.WHITE
                    }
                    ]
               onMousePressed: function(e: MouseEvent): Void {
                    main.logger.addEvent("dialogMap", "btnValider", "previousScreen");
                    choixStation.stationEnCours = listView.selectedItem.toString();
                    zoomLevel = 0;
                    viewportSize = 4240;
                    viewportCenterX = 2120;
                    viewportCenterY = 2120;
                    nearbyStations = [];
                    choixStation.dialog.afficher = false;
                }
                disable: bind (listView.selectedIndex == -1)
}

function updateNearbyStations(x: Integer, y: Integer, r: Integer) : Void {

var name:String;
var xMap:Integer;
var yMap:Integer;
var records = fileDataSource.getDataSource("Worksheet/Table/Row/Cell/Data").getRecordSet().all();
var i:Integer = 0;

nearbyStations = [];

//println("Entrée boucle, {records.size()}");
    while(i < records.size()){
        name = records.get(i).getString(".text");
        xMap = java.lang.Integer.parseInt(records.get(++i).getString(".text"));
        yMap = java.lang.Integer.parseInt(records.get(++i).getString(".text"));
        ++i;
        //println("Testing {name} {x} {y} {(xMap-x)*(xMap-x) + (yMap-y)*(yMap-y)}");
        if((xMap-x)*(xMap-x) + (yMap-y)*(yMap-y) < r*r){
            insert name into nearbyStations;
            //println("Inserting {name}");
        }

            
    }
}



    override public function create(): Node {
        def defMain: Main = main;
        group = Group { content: [
                        iv, zoomIn, zoomOut, goLeft, goRight, goUp, goDown, listView, bouton_etape_prec, bouton_valider
                    ]
                    cache:true;
                    cacheHint: CacheHint.SPEED;
                }
        return group;
    }
}
